import { http } from "@/utils/http";
import type { ApiResponse } from "../../user";
import { ensureArray, normalisePagination, toNumber } from "@/api/_helpers";

const BRAND_ENDPOINT = "/system/product/brand";

export interface BrandListParams {
  page?: number;
  page_size?: number;
  keyword?: string;
  is_visible?: string | number;
  owner_org_id?: string | number;
}

export interface BrandListItem {
  id: number;
  name: string;
  slug: string;
  logo_url?: string | null;
  banner_url?: string | null;
  description?: string | null;
  content?: string | null;
  origin_country?: string | null;
  owner_org_id?: number | null;
  sort: number;
  is_visible: number;
  create_time?: string | null;
  update_time?: string | null;
}

export interface BrandPagination {
  total: number;
  pageSize: number;
  currentPage: number;
}

export interface BrandListResult {
  list: BrandListItem[];
  pagination: BrandPagination;
}

export interface BrandDetail extends BrandListItem {}

export interface BrandSubmitPayload {
  name: string;
  slug: string;
  logo_url?: string;
  banner_url?: string;
  description?: string;
  content?: string;
  origin_country?: string;
  owner_org_id?: number | null;
  sort?: number;
  is_visible?: number | boolean;
}

const mapBrand = (item: Record<string, any>): BrandListItem => ({
  id: toNumber(item.id, 0),
  name: item.name ?? "",
  slug: item.slug ?? "",
  logo_url: item.logo_url ?? null,
  banner_url: item.banner_url ?? null,
  description: item.description ?? null,
  content: item.content ?? null,
  origin_country: item.origin_country ?? null,
  owner_org_id:
    item.owner_org_id !== null && item.owner_org_id !== undefined
      ? toNumber(item.owner_org_id, null)
      : null,
  sort: toNumber(item.sort, 0),
  is_visible: toNumber(item.is_visible, 0),
  create_time: item.create_time ?? null,
  update_time: item.update_time ?? null
});

const mapSubmitPayload = (payload: BrandSubmitPayload): Record<string, any> => {
  const data: Record<string, any> = {
    name: payload.name,
    slug: payload.slug,
    logo_url: payload.logo_url ?? "",
    banner_url: payload.banner_url ?? "",
    description: payload.description ?? "",
    content: payload.content ?? "",
    origin_country: payload.origin_country ?? "",
    owner_org_id:
      payload.owner_org_id !== undefined && payload.owner_org_id !== null
        ? Number(payload.owner_org_id)
        : null,
    sort:
      payload.sort !== undefined && payload.sort !== null
        ? Number(payload.sort)
        : 0,
    is_visible:
      payload.is_visible === undefined || payload.is_visible === null
        ? 1
        : Number(payload.is_visible)
          ? 1
          : 0
  };

  return data;
};

const fetchList = async (
  params: BrandListParams = {}
): Promise<BrandListResult> => {
  const page = toNumber(params.page, 1) || 1;
  const pageSize = toNumber(params.page_size, 10) || 10;

  const res = await http.request<ApiResponse<any>>("get", BRAND_ENDPOINT, {
    params: {
      ...params,
      page,
      page_size: pageSize
    }
  });

  const payload = (res?.data ?? {}) as Record<string, any>;
  const list = ensureArray(payload.list ?? payload.data ?? []).map(mapBrand);
  const pagination = normalisePagination(
    payload.pagination ?? payload,
    page,
    pageSize,
    list.length
  );

  return {
    list,
    pagination: {
      total: pagination.total,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    }
  };
};

const getBrand = async (id: number | string): Promise<BrandDetail> => {
  const res = await http.request<ApiResponse<Record<string, any>>>(
    "get",
    `${BRAND_ENDPOINT}/${id}`
  );
  return mapBrand(res?.data ?? {});
};

const createBrand = async (payload: BrandSubmitPayload) => {
  const data = mapSubmitPayload(payload);
  return http.request<ApiResponse<any>>("post", BRAND_ENDPOINT, { data });
};

const updateBrand = async (
  id: number | string,
  payload: BrandSubmitPayload
) => {
  const data = mapSubmitPayload(payload);
  return http.request<ApiResponse<any>>("put", `${BRAND_ENDPOINT}/${id}`, {
    data
  });
};

const removeBrand = async (id: number | string) => {
  return http.request<ApiResponse<any>>("delete", `${BRAND_ENDPOINT}/${id}`);
};

export default {
  fetchList,
  get: getBrand,
  create: createBrand,
  update: updateBrand,
  remove: removeBrand
};

export { fetchList, getBrand, createBrand, updateBrand, removeBrand };
